package com.example.demo33.util;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    // 注入UserDetailsService（后面会修改这个类，去掉角色）
    private final UserDetailsService userDetailsService;

    // 构造器注入（替代@Autowired，更推荐）
    public SecurityConfig(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf().disable() // 开发环境禁用CSRF
                .authorizeRequests()
                // 允许匿名访问的接口和页面
                .antMatchers("/api/auth/register", "/api/auth/login", "/register", "/login").permitAll()
                // 所有其他请求需要认证（无需角色判断）
                .anyRequest().authenticated()
                .and()
                // 会话管理：同一用户最多1个会话
                .sessionManagement()
                .maximumSessions(1)
                .expiredUrl("/login?expired")
                .and()
                .and()
                // 注销配置
                .logout()
                .invalidateHttpSession(true)
                .clearAuthentication(true)
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login")
                .permitAll()
                // 关联用户详情服务（用于加载用户信息）
                .and()
                .userDetailsService(userDetailsService);

        return http.build();
    }
}